import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, Modal } from 'antd';
import { UndoOutlined, RedoOutlined, CloudOutlined, ShareAltOutlined, DownloadOutlined, 
    AppstoreOutlined, FontSizeOutlined, BlockOutlined, PictureOutlined, BgColorsOutlined, QrcodeOutlined, 
    UploadOutlined, CustomerServiceOutlined, RightOutlined, LeftOutlined, 
    PlusOutlined, MinusOutlined, QuestionCircleOutlined, PieChartOutlined ,BgColorsOutlined as ColorIcon } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import './Layout.css';
import { Rnd } from 'react-rnd';
import ImgPage from './ImgPage';
import Stuff from './components/Stuff';
import yu from '../../assets/themePage/ktu.png'
import Cropper from 'react-cropper';
import HelpCenterPopup from './components/Ask';


interface CanvasItem {
  id: string;
  type: string;
  x: number;
  y: number;
  width: number;
  height: number;
  img?: string;
  name?: string;
  text?: string;
  color?: string;
  fontSize?: number;
}

// 最左边标签
const tabs = [
  { key: 'template', label: '模板', icon: <AppstoreOutlined /> },
  { key: 'text', label: '文字', icon: <FontSizeOutlined /> },
  { key: '3dtext', label: '3D文字', icon: <BlockOutlined /> },
  { key: 'material', label: '素材', icon:    <PieChartOutlined /> },
  { key: 'image', label: '图片', icon: <PictureOutlined /> },
  { key: 'background', label: '背景', icon: <BgColorsOutlined /> },
  { key: 'qrcode', label: '二维码', icon: <QrcodeOutlined /> },
  { key: 'upload', label: '上传', icon: <UploadOutlined /> },
];

// 每个标签的收缩内容（可点击高亮）
const panelItems: Record<string, { id: string; name: string; img?: string }[]> = {
  template: [
    { id: 't1', name: '模板A' },
    { id: 't2', name: '模板B' },
    { id: 't3', name: '模板C' },
  ],
  text: [
    { id: 'tx1', name: '大标题', img: 'https://img1.baidu.com/it/u=5678901234,5678901234&fm=253&fmt=auto&app=138&f=JPEG?w=100&h=40' },
    { id: 'tx2', name: '副标题', img: 'https://img1.baidu.com/it/u=6789012345,6789012345&fm=253&fmt=auto&app=138&f=JPEG?w=100&h=40' },
  ],
  '3dtext': [
    { id: 'd1', name: '3D字1' },
    { id: 'd2', name: '3D字2' },
  ],
  material: [
    { id: 'm1', name: '红色装饰', img: 'https://img1.baidu.com/it/u=3456789012,3456789012&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200' },
    { id: 'm2', name: '金色边框', img: 'https://img1.baidu.com/it/u=4567890123,4567890123&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200' },
  ],
  image: [
    { id: 'i1', name: '向日葵', img: 'https://img1.baidu.com/it/u=1234567890,1234567890&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333' },
    { id: 'i2', name: '绿叶', img: 'https://img1.baidu.com/it/u=2345678901,2345678901&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=333' },
  ],
  background: [
    { id: 'b1', name: '背景1' },
    { id: 'b2', name: '背景2' },
  ],
  qrcode: [
    { id: 'q1', name: '二维码1' },
    { id: 'q2', name: '二维码2' },
  ],
  upload: [
    { id: 'u1', name: '上传文件1' },
    { id: 'u2', name: '上传文件2' },
  ],
};

// 右侧编辑区内容
const EditPanel: React.FC<{ 
  activeTab: string; 
  onEditSize: () => void; 
  onColorPick: () => void; 
  color: string;
  canvasSize: { width: number; height: number };
}> = ({ activeTab, onEditSize, onColorPick, color, canvasSize }) => {
  if (activeTab === 'template' || activeTab === 'material' || activeTab === 'image' || activeTab === 'background' || activeTab === 'qrcode' || activeTab === 'upload' || activeTab === '3dtext') {
    return (
      <div className="nc-edit-panel-inner">
        <div className="nc-edit-title">画布编辑</div>
        <div className="nc-edit-label-row">
          <span className="nc-edit-label">画布尺寸</span>
          <Button type="link" className="nc-edit-link" onClick={onEditSize}>编辑</Button>
        </div>
        <div className="nc-edit-size-row">
          <Input value={`${canvasSize.width}px`} readOnly className="nc-edit-size-input" suffix="宽" style={{ width: 100, marginRight: 8 }} onClick={onEditSize} />
          <Input value={`${canvasSize.height}px`} readOnly className="nc-edit-size-input" suffix="高" style={{ width: 100 }} onClick={onEditSize} />
        </div>
        <div className="nc-edit-label">画布颜色</div>
        <div className="nc-edit-color-row">
          <Input value={color} readOnly className="nc-edit-color-input" style={{ width: 180, marginRight: 8 }} onClick={onColorPick} />
          <Button icon={<ColorIcon />} onClick={onColorPick} className="nc-edit-color-btn" style={{ background: color, border: '1px solid #eee' }} />
        </div>
      </div>
    );
  }
  return null;
};

// 图片裁剪模态框组件
const ImageCropModal: React.FC<{ 
  visible: boolean; 
  imageUrl: string;
  onCancel: () => void;
  onCrop: (croppedImage: string) => void;
}> = ({ visible, imageUrl, onCancel, onCrop }) => {
  const cropperRef = useRef<any>(null);
  const [aspectRatio, setAspectRatio] = useState<number | undefined>(undefined);

  const getCroppedImage = () => {
    if (cropperRef.current && cropperRef.current.cropper) {
      const cropper = cropperRef.current.cropper;
      const canvas = cropper.getCroppedCanvas();
      const imageUrl = canvas.toDataURL('image/png');
      onCrop(imageUrl);
      onCancel();
    }
  };

  return (
    <Modal
      title="图片裁剪"
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button key="free" onClick={() => setAspectRatio(undefined)} style={{ marginRight: 'auto' }}>
          自由裁剪
        </Button>,
        <Button key="square" onClick={() => setAspectRatio(1)}>
          1:1
        </Button>,
        <Button key="portrait" onClick={() => setAspectRatio(4/5)}>
          4:5
        </Button>,
        <Button key="landscape" onClick={() => setAspectRatio(16/9)}>
          16:9
        </Button>,
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="crop" type="primary" onClick={getCroppedImage}>
          确认裁剪
        </Button>
      ]}
    >
      <div style={{ width: '100%', height: '500px' }}>
        <Cropper
          src={imageUrl}
          style={{ height: '100%', width: '100%' }}
          aspectRatio={aspectRatio}
          guides={true}
          ref={cropperRef}
          viewMode={1}
          rotatable={true}
          background={false}
          responsive={true}
          dragMode="move"
          autoCropArea={0.8}
          restore={false}
          modal={true}
          movable={true}
          scalable={true}
          zoomable={true}
          highlight={false}
          cropBoxMovable={true}
          cropBoxResizable={true}
        />
      </div>
    </Modal>
  );
};

// 新增图片编辑区组件
const ImageEditPanel: React.FC<{ 
  item: CanvasItem | null;
  onReplaceImage: () => void;
  onCropImage: () => void;
  onTransparencyChange: (value: number) => void;
}> = ({ item, onReplaceImage, onCropImage, onTransparencyChange }) => {
    const navigate=useNavigate()
  if (!item) return null;

  return (
    <div style={{ padding: 20 }}>
      <div style={{ fontWeight: 600, fontSize: 18, marginBottom: 16 }}>图片编辑</div>
      <Button 
        style={{ width: '100%', marginBottom: 20, color: '#ff9900', border: '1px solid #ff9900', background: '#fffbe6' }}
        onClick={onReplaceImage}
      >
        替换图片
      </Button>
      <div style={{ fontWeight: 500, marginBottom: 8 }}>裁剪</div>
      <Button 
        style={{ width: '100%', marginBottom: 8 }} 
        icon={<span style={{ fontSize: 18 }}>▭</span>}
        onClick={onCropImage}
      >
        裁剪图片
      </Button>
      <Button style={{ width: '100%', marginBottom: 16 }} icon={<span style={{ fontSize: 18 }}>⊘</span>}>形状裁剪</Button>
      <div style={{ fontWeight: 500, marginBottom: 8 }}>翻转</div>
      <Button style={{ width: '100%', marginBottom: 8 }} icon={<span style={{ fontSize: 18 }}>⇋</span>}>水平翻转</Button>
      <Button style={{ width: '100%', marginBottom: 16 }} icon={<span style={{ fontSize: 18 }}>⇅</span>}>垂直翻转</Button>
      <div style={{ fontWeight: 500, marginBottom: 8 }}>透明度</div>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
        <span style={{ color: '#888', marginRight: 8 }}>不透明</span>
        <input 
          type="range" 
          min={0} 
          max={100} 
          defaultValue={100} 
          style={{ flex: 1 }} 
          onChange={(e) => onTransparencyChange(Number(e.target.value))}
        />
        <span style={{ marginLeft: 8 }}>100%</span>
      </div>
      <div style={{ fontWeight: 500, marginBottom: 8 }}>抠图</div>
      <div onClick={()=> navigate('/CutImage')} style={{ background: '#fffbe6', borderRadius: 8, marginBottom: 24 }}>
        <img src={yu} alt="抠图" style={{ width: '100%', height: 80, marginRight: 12  }} /> 
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
        <Button icon={<span style={{ fontSize: 18 }}>⎌</span>} style={{ flex: 1 }} />
        <Button icon={<span style={{ fontSize: 18 }}>⧉</span>} style={{ flex: 1 }} />
        <Button icon={<span style={{ fontSize: 18 }}>🗑️</span>} style={{ flex: 1 }} />
      </div>
    </div>
  );
};

const Layout: React.FC = () => {
  // 获取当前路由信息
  const location = useLocation();
  // 设置画布尺寸
  const [canvasSize, setCanvasSize] = useState({ width: 900, height: 383 });
  // 设置当前激活的标签页
  const [activeTab, setActiveTab] = useState('material');
  // 设置是否显示侧边栏
  const [showSidebar, setShowSidebar] = useState(true);
  // 设置画布缩放比例
  const [canvasScale, setCanvasScale] = useState(1.14); // 默认114%
  // 设置当前弹窗类型
  const [modalType, setModalType] = useState<'watermark' | 'help' | 'size' | 'color' | 'replaceImage' | null>(null);
  // 设置裁剪模态框状态
  const [cropModalVisible, setCropModalVisible] = useState(false);
  // 设置当前选中的面板项
  const [selectedPanelItem, setSelectedPanelItem] = useState<string>('');
  // 设置画布上的元素
  const [canvasItems, setCanvasItems] = useState<CanvasItem[]>([]);
  // 设置当前选中的元素ID
  const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
// 问题
 const [showPopup, setShowPopup] = useState(false);


 

  // 从路由参数中获取画布尺寸

  useEffect(() => {
    if (location.state?.width && location.state?.height) {
      setCanvasSize({
        width: location.state.width,
        height: location.state.height
      });
    }
  }, [location]);

  // 缩放处理
  const handleZoom = (type: 'in' | 'out') => {
    setCanvasScale(prev => {
      let next = type === 'in' ? prev + 0.1 : prev - 0.1;
      if (next > 2) next = 2;
      if (next < 0.1) next = 0.1;
      return Math.round(next * 100) / 100;
    });
  };

  // 颜色选择
  const handleColorPick = () => {
    setModalType('color');
  };

  // 自动展开收缩框
  const handleTabClick = (key: string) => {
    setActiveTab(key);
    setShowSidebar(true);
    setSelectedPanelItem('');
  };

  // 左侧收缩内容区
  const renderSidebarPanel = () => (
    <div className="nc-left-panel">
      <div className="nc-panel-list">
        {activeTab === 'image' ? (
          <ImgPage />
        ) : activeTab === 'material' ? (
          <Stuff />
        ) : (
          panelItems[activeTab]?.map(item => (
            <div
              key={item.id}
              className={`nc-panel-list-item${selectedPanelItem === item.id ? ' selected' : ''}`}
              onClick={() => handleAddItemFromPanel(item)}
              style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', marginBottom: 12 }}
            >
              {item.img && (
                <img
                  src={item.img}
                  alt={item.name}
                  style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 6, marginRight: 8, border: '1px solid #eee' }}
                />
              )}
              <span>{item.name}</span>
            </div>
          ))
        )}
      </div>
      <div className="nc-left-panel-arrow" onClick={() => setShowSidebar(false)}>
        <RightOutlined className='nc-left-panel-arrow-collapsed-icon' />
      </div>
    </div>
  );

  const handleAddItemFromPanel = (item: { id: string; name: string; img?: string }) => {
    const id = Date.now().toString();
    let newItem: CanvasItem;
    
    if (activeTab === 'image' || activeTab === 'material') {
      newItem = {
        id,
        type: activeTab,
        x: 120,
        y: 120,
        width: 240,
        height: 180,
        img: item.img,
        name: item.name,
      };
    } else if (activeTab === 'text') {
      newItem = {
        id,
        type: 'text',
        x: 150,
        y: 150,
        width: 180,
        height: 50,
        text: item.name,
        color: '#333',
        fontSize: 24,
      };
    } else {
      return;
    }
    
    setCanvasItems(items => [...items, newItem]);
    setSelectedItemId(id);
  };

  // 裁剪图片
  const handleCropImage = () => {
    setCropModalVisible(true);
  };

  // 应用裁剪结果
  const handleApplyCrop = (croppedImage: string) => {
    if (selectedItemId) {
      setCanvasItems(items => 
        items.map(item => 
          item.id === selectedItemId ? { ...item, img: croppedImage } : item
        )
      );
    }
    setCropModalVisible(false);
  };

  // 替换图片
  const handleReplaceImage = () => {
    setModalType('replaceImage');
  };

  // 透明度变化处理
  const handleTransparencyChange = (value: number) => {
    console.log(`设置透明度为: ${value}%`);
    // 这里可以添加实际设置透明度的逻辑
  };

  // 画布区域支持拖拽
  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const type = e.dataTransfer.getData('type');
    const imgUrl = e.dataTransfer.getData('img');
    const name = e.dataTransfer.getData('name');
    
    // 计算相对于画布的位置
    const rect = e.currentTarget.getBoundingClientRect();
    const x = (e.clientX - rect.left) / canvasScale;
    const y = (e.clientY - rect.top) / canvasScale;

    const id = Date.now().toString();
    let newItem: CanvasItem;

    if (type === 'image') {
      newItem = {
        id,
        type: 'image',
        x,
        y,
        width: 200,
        height: 150,
        img: imgUrl,
        name,
      };
    } else {
      return;
    }

    setCanvasItems(items => [...items, newItem]);
    setSelectedItemId(id);
  };

  // 获取当前选中图片URL
  const getSelectedImageUrl = () => {
    if (!selectedItemId) return '';
    const selectedItem = canvasItems.find(item => item.id === selectedItemId);
    return selectedItem?.img || '';
  };

  return (
    <div className="nc-root">
      {/* 头部 */}
      <div className="nc-header-bar">
        <div className="nc-header-left">
          <span className="nc-title">包图·在线设计</span>
        </div>
        <div className="nc-header-center">
          <span className="nc-header-menu">文件</span>
          <span className="nc-header-menu">视图</span>
          <UndoOutlined className="nc-header-icon" title="撤销" />
          <RedoOutlined className="nc-header-icon" title="重做" />
          <CloudOutlined className="nc-header-icon" title="云存储" />
          <span className="nc-header-menu">会议背景</span>
        </div>
        <div className="nc-header-right">
          <div className='nc-bg'></div>
          <Button type="link" className="nc-header-btn">加入会员</Button>
          <Button icon={<ShareAltOutlined />} className="nc-header-btn">分享</Button>
          <Button type="primary" icon={<DownloadOutlined />} className="nc-header-btn nc-header-download">无水印下载</Button>
        </div>
      </div>
      <div className="nc-main">
        {/* 左侧标签栏 */}
        <div className="nc-sidebar">
          <div className="nc-sidebar-tabs">
            {tabs.map(tab => (
              <div
                key={tab.key}
                className={`nc-tab${activeTab === tab.key ? ' active' : ''}`}
                onClick={() => handleTabClick(tab.key)}
              >
                <div className="nc-tab-icon">{tab.icon}</div>
                <div className="nc-tab-label">{tab.label}</div>
              </div>
            ))}
          </div>
          <div className="nc-sidebar-bottom">
            <CustomerServiceOutlined className="nc-customer-icon" />
            <div className="nc-customer-label">联系客服</div>
          </div>
        </div>
        {/* 左侧收缩内容区 */}
        {showSidebar && renderSidebarPanel()}
        {!showSidebar && (
          <div className="nc-left-panel-arrow-collapsed" onClick={() => setShowSidebar(true)}>
            <LeftOutlined  className='nc-left-panel-arrow-collapsed-icon'/>
          </div>
        )}
        {/* 中间画布 */}
        <div className="nc-canvas">
          <div
            className="nc-canvas-inner"
            style={{
              width: `${canvasSize.width * canvasScale}px`,
              height: `${canvasSize.height * canvasScale}px`,
              background: '#fff',
              transition: 'width 0.2s, height 0.2s, background 0.2s',
            }}
            onDrop={handleDrop}
            onDragOver={e => e.preventDefault()}
          >
            {canvasItems.map(item => (
              <Rnd
                key={item.id}
                size={{ width: item.width, height: item.height }}
                position={{ x: item.x, y: item.y }}
                onDragStop={(e, d) => {
                  setCanvasItems(items => items.map(it => it.id === item.id ? { ...it, x: d.x, y: d.y } : it));
                }}
                onResizeStop={(e, dir, ref, delta, pos) => {
                  setCanvasItems(items => items.map(it => it.id === item.id ? {
                    ...it,
                    width: ref.offsetWidth,
                    height: ref.offsetHeight,
                    x: pos.x,
                    y: pos.y
                  } : it));
                }}
                onClick={() => setSelectedItemId(item.id)}
                style={{
                  border: selectedItemId === item.id ? '2px solid #4096ff' : 'none',
                  zIndex: selectedItemId === item.id ? 10 : 1,
                  position: 'absolute',
                  opacity: item.type === 'image' || item.type === 'material' ? item.color?.includes('opacity') ? 0.8 : 1 : 1
                }}
                bounds="parent"
              >
                {item.type === 'image' || item.type === 'material' ? (
                  <img 
                    src={item.img} 
                    alt={item.name} 
                    style={{ width: '100%', height: '100%' }} 
                  />
                ) : item.type === 'text' ? (
                  <div style={{ color: item.color, fontSize: item.fontSize }}>{item.text}</div>
                ) : null}
              </Rnd>
            ))}
          </div>
          {/* 底部操作条 */}
          <div className="nc-canvas-footer">
            <Button
              className="nc-canvas-footer-btn"
              onClick={() => setModalType('watermark')}
            >
              移除水印，畅享高清模版
            </Button>
            <div className="nc-canvas-footer-zoom">
              <Button
                icon={<MinusOutlined />}
                onClick={() => handleZoom('out')}
                disabled={canvasScale <= 0.1}
                className="nc-canvas-footer-zoom-btn"
              />
              <span className="nc-canvas-footer-zoom-text">{Math.round(canvasScale * 100)}%</span>
              <Button
                icon={<PlusOutlined />}
                onClick={() => handleZoom('in')}
                disabled={canvasScale >= 2}
                className="nc-canvas-footer-zoom-btn"
              />
            </div>
            <Button
              shape="circle"
              icon={<QuestionCircleOutlined />}
              className="nc-canvas-footer-help"
              onClick={() =>setShowPopup(true)}
            />
             {showPopup && (
        <HelpCenterPopup onClose={() => setShowPopup(false)} />
      )}
          </div>
        </div>
        {/* 右侧画布编辑区 */}
        <div className="nc-edit-panel">
          {(selectedItemId && ['image', 'material', 'background'].includes((canvasItems.find(i => i.id === selectedItemId)?.type || ''))) ? (
            <ImageEditPanel 
              item={canvasItems.find(i => i.id === selectedItemId) || null}
              onReplaceImage={handleReplaceImage}
              onCropImage={handleCropImage}
              onTransparencyChange={handleTransparencyChange}
            />
          ) : (
            <EditPanel
              activeTab={activeTab}
              onEditSize={() => setModalType('size')}
              onColorPick={handleColorPick}
              color='#fff'
              canvasSize={canvasSize}
            />
          )}
        </div>
      </div>
      {/* 裁剪模态框 */}
      <ImageCropModal 
        visible={cropModalVisible}
        imageUrl={getSelectedImageUrl()}
        onCancel={() => setCropModalVisible(false)}
        onCrop={handleApplyCrop}
      />
      {/* 其他弹窗 */}
      <Modal
        open={modalType === 'watermark'}
        onCancel={() => setModalType(null)}
        title="移除水印"
        footer={null}
      >
        <div style={{ textAlign: 'center', fontSize: 18, padding: 24 }}>请登录或开通会员以移除水印，畅享高清模版！</div>
      </Modal>
 
      <Modal
        open={modalType === 'size'}
        onCancel={() => setModalType(null)}
        title="编辑画布尺寸"
        onOk={() => setModalType(null)}
      >
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 16 }}>
          <Input addonAfter="宽" defaultValue={canvasSize.width} style={{ width: 120 }} />
          <Input addonAfter="高" defaultValue={canvasSize.height} style={{ width: 120 }} />
        </div>
        <div style={{ color: '#888' }}>请输入画布宽高(px),范围建议100~2000</div>
      </Modal>
      <Modal
        open={modalType === 'replaceImage'}
        onCancel={() => setModalType(null)}
        title="替换图片"
        footer={[
          <Button key="cancel" onClick={() => setModalType(null)}>
            取消
          </Button>,
          <Button key="upload" type="primary" onClick={() => setModalType(null)}>
            上传图片
          </Button>
        ]}
      >
        <div style={{ textAlign: 'center', padding: '20px 0' }}>
          <UploadOutlined style={{ fontSize: 48, color: '#1890ff' }} />
          <p>拖拽图片到此处或点击上传新图片</p>
        </div>
      </Modal>
    </div>
  );
};

export default Layout;